package com.symaster.backups.frame.page.configs.items;

import com.symaster.backups.enumerate.BackupFolderPathType;
import com.symaster.backups.enumerate.SystemConfig;
import com.symaster.backups.frame.dialog.BackupFileMove;
import com.symaster.backups.frame.element.layout.TileLayout;
import com.symaster.backups.frame.page.configs.ConfigItem;
import com.symaster.backups.model.SystemConfigModel;
import com.symaster.backups.repository.SystemConfigRepository;
import com.symaster.backups.service.SystemConfigService;
import com.symaster.common.swing.util.SwingUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * @author yinmiao
 * @version 2024/2/26
 */
@Component
public class BackupConfig extends ConfigItem {

    private final SystemConfigRepository systemConfigRepository;
    private final SystemConfigService systemConfigService;
    private final BackupFileMove backupFileMove;

    private JComboBox<BackupFolderPathType> backupFolderPathTypeJComboBox;
    private JTextField backupFolderInput;

    @Autowired
    public BackupConfig(SystemConfigRepository systemConfigRepository, SystemConfigService systemConfigService, BackupFileMove backupFileMove) {
        this.systemConfigRepository = systemConfigRepository;
        this.systemConfigService = systemConfigService;
        this.backupFileMove = backupFileMove;
    }

    private JComponent backupFileConfig() {
        JPanel jPanel1 = new JPanel();
        jPanel1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        jPanel1.add(new JLabel("备份文件存放目录"));

        backupFolderInput = new JTextField();
        backupFolderInput.setPreferredSize(new Dimension(200, 23));
        backupFolderInput.setVisible(false);
        backupFolderInput.addActionListener(e -> {
            if (StringUtils.isEmpty(backupFolderInput.getText())) {
                return;
            }

            File file = new File(backupFolderInput.getText());
            if (!file.isDirectory() && !file.mkdirs()) {
                JOptionPane.showMessageDialog(this, "你输入的路径不是文件夹并且创建失败", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int i = JOptionPane.showConfirmDialog(this, "选择'是'将会修改并且自动迁移当前备份目录, 取消操作请选'否'\n请注意: 根据备份目录大小不同所需耗时也不同,在迁移过程中程序将会暂停备份", "提示", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (i == 0) {
                String parent = systemConfigService.backupFolderRoot();

                backupFileMove.setLocation(backupFolderInput.getLocationOnScreen());
                backupFileMove.open(parent, file.toPath().toString());

                SystemConfigModel systemConfigModel = systemConfigRepository.findByKey(SystemConfig.BACKUP_FOLDER_PATH_TYPE.getKey()).orElse(new SystemConfigModel());
                systemConfigModel.setConfigKey(SystemConfig.BACKUP_FOLDER_PATH_TYPE.getKey());
                systemConfigModel.setCreatedTime(systemConfigModel.getCreatedTime() == null ? new Date() : systemConfigModel.getCreatedTime());
                systemConfigModel.setUpdatedTime(new Date());
                systemConfigModel.setDeleteStatus(false);
                systemConfigModel.setStringValue(BackupFolderPathType.CUSTOM_PATH.getKey());
                systemConfigRepository.save(systemConfigModel);

                SystemConfigModel systemConfigModel1 = systemConfigRepository.findByKey(SystemConfig.BACKUP_FOLDER.getKey()).orElse(new SystemConfigModel());
                systemConfigModel1.setConfigKey(SystemConfig.BACKUP_FOLDER.getKey());
                systemConfigModel1.setDeleteStatus(false);
                systemConfigModel1.setCreatedTime(systemConfigModel1.getCreatedTime() == null ? new Date() : systemConfigModel1.getCreatedTime());
                systemConfigModel1.setUpdatedTime(new Date());
                systemConfigModel1.setStringValue(file.toPath().toString());
                systemConfigRepository.save(systemConfigModel1);
            }
        });

        JButton jButton = new JButton(SwingUtil.loadIcon("folder.png", 13, 13));
        jButton.setMargin(new Insets(4, 4, 4, 4));
        jButton.setVisible(false);
        jButton.addActionListener(e -> {
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int i = jFileChooser.showOpenDialog(this);
            if (i == JFileChooser.APPROVE_OPTION) {
                backupFolderInput.setText(jFileChooser.getSelectedFile().getAbsolutePath());
            }
        });

        backupFolderPathTypeJComboBox = new JComboBox<>();
        for (BackupFolderPathType value : BackupFolderPathType.values()) {
            backupFolderPathTypeJComboBox.addItem(value);
        }
        backupFolderPathTypeJComboBox.addActionListener(e -> {
            boolean visible = Objects.equals(backupFolderPathTypeJComboBox.getSelectedItem(), BackupFolderPathType.CUSTOM_PATH);
            backupFolderInput.setVisible(visible);
            jButton.setVisible(visible);
        });

        jPanel1.add(backupFolderPathTypeJComboBox);
        jPanel1.add(backupFolderInput);
        jPanel1.add(jButton);
        return jPanel1;
    }

    private JComponent timeDeleteConfig() {
        JPanel jPanel1 = new JPanel();
        jPanel1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        jPanel1.setOpaque(false);

        jPanel1.add(new JCheckBox("自动清理备份文件"));
        jPanel1.add(new JLabel("保留版本数量"));

        SpinnerNumberModel model = new SpinnerNumberModel(0, 0, 100, 1); // 初始值为0，范围从0到100，步长为1
        JSpinner jSpinner = new JSpinner(model);
        jPanel1.add(jSpinner);

        return jPanel1;
    }

    @Override
    public String label() {
        return "备份设置";
    }

    @Override
    public void viewEvent() {
        removeAll();
        setLayout(new TileLayout());
        add(backupFileConfig());
        add(timeDeleteConfig());

        Optional<SystemConfigModel> byKey = systemConfigRepository.findByKey(SystemConfig.BACKUP_FOLDER_PATH_TYPE.getKey());
        if (byKey.isPresent()) {
            backupFolderPathTypeJComboBox.setSelectedItem(BackupFolderPathType.ofKey(byKey.get().getStringValue()));
        } else {
            backupFolderPathTypeJComboBox.setSelectedItem(BackupFolderPathType.APPLICATION_ROOT);
        }

        systemConfigRepository.findByKey(SystemConfig.BACKUP_FOLDER.getKey())
                .ifPresent(e -> backupFolderInput.setText(e.getStringValue()));
    }
}
